﻿using LogisticsTrackingWebApi_V2.Models;
using LogisticsTrackingWebApi_V2.Services;

namespace LogisticsTrackingWebApi_V2.ServicesImpl
{

    /// <summary>
    /// 物流服务实现
    /// </summary>
    public class LogisticsService : ILogisticsService
    {
        private readonly ILogisticsProviderFactory _providerFactory;

        public LogisticsService(ILogisticsProviderFactory providerFactory)
        {
            _providerFactory = providerFactory;
        }

        public IEnumerable<(string Code, string Name)> GetSupportedCompanies()
        {
            return _providerFactory.GetAllProviders()
                .Select(p => (p.CompanyCode, p.CompanyName));
        }

        public async Task<LogisticsInfo> QueryLogisticsAsync(string trackingNumber, string? companyCode = null)
        {
            if (string.IsNullOrWhiteSpace(trackingNumber))
            {
                throw new ArgumentException("物流单号不能为空", nameof(trackingNumber));
            }

            ILogisticsProvider provider;

            if (!string.IsNullOrEmpty(companyCode))
            {
                // 如果指定了公司代码，直接获取对应的提供者
                provider = _providerFactory.GetProvider(companyCode);
            }
            else
            {
                // 如果没有指定公司代码，尝试猜测
                provider = _providerFactory.GuessProvider(trackingNumber);
                if (provider == null)
                {
                    throw new InvalidOperationException("无法识别物流公司，请指定公司代码");
                }
            }

            // 使用选定的提供者查询物流信息
            return await provider.QueryLogisticsAsync(trackingNumber);
        }
    }

}
